package com.tmc.platform.ctrip;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.util.Date;

import javax.xml.rpc.ServiceException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.core.util.Base64Encoder;
import com.tmc.entity.intair.CommisionPolicy;
import com.tmc.platform.ctrip.bean.PublishFareInfo;
import com.tmc.platform.ctrip.bean.PublishFareResponse;
import com.tmc.platform.ctrip.util.CtripPolicyUtil;
import com.tmc.platform.ctrip.util.GetStubUtil;
import com.tmc.platform.ctrip.util.XStreamUtil;
import com.tmc.service.intair.CommisionPolicyServiceImpl;
import com.tmc.util.Base64Util;
import com.tmc.util.DateUtil;
import com.tmc.util.HttpClientUtil;
import com.tmc.util.MD5Util;
import com.tmc.util.ZipUtil;

@Service
public class CtripServiceImpl implements CtripService {

	//private Log logger = LogFactory.getLog(CtripServiceImpl.class);

	/**
	 * 今日出票单接口
	 * 
	 * @throws IOException
	 * @throws ServiceException
	 * @throws RemoteException
	 */
	@Override
	public String openIssueOrderList(Date orderBeginDateTime, Date orderEndDateTime) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenIssueOrderListRequest>";
			xml += "<OrderBeginDateTime>"
					+ DateUtil.toStrDate(orderBeginDateTime, "yyyy-MM-dd HH:mm:ss").replace(" ", "T")
					+ "</OrderBeginDateTime>";
			xml += "<OrderEndDateTime>" + DateUtil.toStrDate(orderEndDateTime, "yyyy-MM-dd HH:mm:ss").replace(" ", "T")
					+ "</OrderEndDateTime>";
			xml += "</OpenIssueOrderListRequest>";
			xml += "</Request>";
			String responseContent = GetStubUtil.getOpenIssueOrderListSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 出票单详情接口
	 */
	@Override
	public String issueBillInfo(Long issueBillID) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenIssueBillInfoRequest>";
			xml += "<IssueBillID>" + issueBillID + "</IssueBillID>";
			xml += "</OpenIssueBillInfoRequest>";
			xml += "</Request>";
			String responseContent = GetStubUtil.getIssueBillInfoSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 退票查询接口
	 */
	@Override
	public String refundWaitConfirmList(Integer isInternational, Date startRefundDate, Date endRefundDate) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenRefundWaitConfirmListRequest>";
			xml += "<IsInternational>" + isInternational + "</IsInternational>";
			xml += "<StartRefundDate>" + DateUtil.toStrDate(startRefundDate, "yyyy-MM-dd") + "</StartRefundDate>";
			xml += "<EndRefundDate>" + DateUtil.toStrDate(endRefundDate, "yyyy-MM-dd") + "</EndRefundDate>";
			xml += "</OpenRefundWaitConfirmListRequest>";
			xml += "</Request>";
			String responseContent = GetStubUtil.getRefundWaitConfirmListSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 退票确认接口
	 */
	@Override
	public String refundConfirm(String orderId, String prid) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenRefundConfirmRequest>";
			xml += "<OpenRefundConfirmItems>";
			xml += "<OpenRefundConfirmItem>";
			xml += "<OrderId>" + orderId + "</OrderId>";
			xml += "<Prid>" + prid + "</Prid>";
			xml += "</OpenRefundConfirmItem>";
			xml += "</OpenRefundConfirmItems>";
			xml += "</OpenRefundConfirmRequest>";
			xml += "</Request>";
			String responseContent = GetStubUtil.getRefundConfirmSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 票号回填接口
	 */
	@Override
	public String SearchModifyOrderInfo(String bookingChannel, String extOrderID, Long issueBillID,
			Integer dataChangeType, String pnr, Integer pnrResultStatus, String officeNo, Integer sequence,
			String dPort, String aPort, String flightNo, String subClass, String checkChannel, String ticketNo,
			String airLineCode, Integer ticketResultStatus, String passengerName, Integer agencyTicketTax,
			String lcType) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "";
			xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenModifyOrderRequest>";
			if (lcType.equalsIgnoreCase("N")) {
				/*
				 * xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; xml +=
				 * "<Request UserName=\""+username+"\" UserPassword=\""+md5_password+"\">"; xml
				 * += "<OpenModifyOrderRequest>";
				 */
				xml += "<BookingChannel/> <ExtOrderID>" + extOrderID + "</ExtOrderID>";
				xml += "<IssueBillID>" + issueBillID + "</IssueBillID> <DataChangeType>" + dataChangeType
						+ "</ DataChangeType>";
				xml += "<PNRLists> <PNRList>";
				xml += "<PNR>" + pnr + "</PNR> <OfficeNo>" + officeNo + "</OfficeNo> <PNRResultStatus>"
						+ pnrResultStatus + "</PNRResultStatus>";
				xml += "<Sequence>" + sequence + "</Sequence> <DPort>" + dPort + "</DPort> <APort>" + aPort
						+ "</APort>";
				xml += "<FlightNo>" + flightNo + "</FlightNo> <SubClass>" + subClass
						+ "</SubClass> <!--第一程--> <TicketLists>";
				xml += "<TicketList> <!--第一程第一位乘机人-->";
				xml += "<PassengerName>" + passengerName + "</PassengerName> <AirLineCode>" + airLineCode
						+ "</AirLineCode> <TicketNo>" + ticketNo + "</TicketNo>";
				xml += "<TicketResultStatus>" + ticketResultStatus + "</TicketResultStatus> <AgencyTicketTax>"
						+ agencyTicketTax + "</AgencyTicketTax>";
				/*
				 * xml += "</TicketList>"; xml +=
				 * "<TicketList> <!--第一程第二位乘机人--> <PassengerName>孙天浩</PassengerName> <AirLineCode>731</AirLineCode>"
				 * ; xml +=
				 * "<TicketNo>0002009397</TicketNo> <TicketResultStatus>1</TicketResultStatus>";
				 * xml += "<AgencyTicketTax>10</AgencyTicketTax>"; xml += "</TicketList>";
				 */
				xml += "</TicketLists>";
				xml += "</PNRList> </PNRLists>";
				xml += "</OpenModifyOrderRequest> </Request>";
			} else if (lcType.equalsIgnoreCase("Y")) {
				xml += "<BookingChannel/> <ExtOrderID>" + extOrderID + "</ExtOrderID>";
				xml += "<IssueBillID>" + issueBillID + "</IssueBillID> <DataChangeType>" + dataChangeType
						+ "</ DataChangeType>";
				xml += "<PNRLists> <PNRList>";
				xml += "<PNR>" + pnr + "</PNR> <OfficeNo>" + officeNo + "</OfficeNo> <PNRResultStatus>"
						+ pnrResultStatus + "</PNRResultStatus>";
				xml += "<Sequence>" + sequence + "</Sequence>";
				xml += "<DPort>" + dPort + "</DPort> <APort>" + aPort + "</APort> <FlightNo>" + flightNo
						+ "</FlightNo>";
				xml += "<SubClass>" + subClass + "</SubClass> <!--第一程--> <TicketLists>";
				xml += "<TicketList> <PassengerName>" + passengerName + "</PassengerName> <!--第一程第一位乘机人-->";
				xml += "<AirLineCode>" + airLineCode + "</AirLineCode> <TicketNo>" + ticketNo
						+ "</TicketNo> <!--同PNR票号相同-->";
				xml += "<TicketResultStatus>" + ticketResultStatus + "</TicketResultStatus> <AgencyTicketTax>"
						+ agencyTicketTax + "</AgencyTicketTax>";
				xml += "</TicketList>";
				/*
				 * xml += " <TicketList>"; xml +=
				 * "<PassengerName>何分田</PassengerName> <!--第一程第二位乘机人--> <AirLineCode>781</AirLineCode>"
				 * ; xml +=
				 * "<TicketNo>2177658387</TicketNo> <TicketResultStatus>1</TicketResultStatus>";
				 * xml += "<AgencyTicketTax>10</AgencyTicketTax>"; xml += "</TicketList> ";
				 */
				xml += "</TicketLists>";
				xml += "</PNRList> <PNRList>";
				xml += "<PNR>HDH1V7</PNR> <PNRResultStatus>1</PNRResultStatus> <Sequence>2</Sequence>";
				xml += "<OfficeNo>SHA777</OfficeNo> <DPort>CTO</DPort> <APort>BJS</APort>";
				xml += "<FlightNo>MU517</FlightNo> <SubClass>S</SubClass>";
				xml += "<!--第二程--> <TicketLists> <TicketList>";
				xml += "<PassengerName>PASTORE/MARIO</PassengerName> <!--第二程第一位乘机人--> <AirLineCode>781</AirLineCode>";
				xml += "<TicketNo>2177658388</TicketNo> <!--同PNR票号相同--> <TicketResultStatus>1</TicketResultStatus>";
				xml += "<AgencyTicketTax>10</AgencyTicketTax>";
				xml += "</TicketList> <TicketList>";
				xml += "<PassengerName>何分田</PassengerName> <!--第二程第二位乘机人--> <AirLineCode>781</AirLineCode>";
				xml += "<TicketNo>2177658387</TicketNo> <TicketResultStatus>1</TicketResultStatus>";
				xml += "<AgencyTicketTax>10</AgencyTicketTax>";
				xml += "</TicketList> </TicketLists>";
				xml += "</PNRList> </PNRLists>";
				xml += "</OpenModifyOrderRequest> </Request>";
			}
			String responseContent = GetStubUtil.getRefundConfirmSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 改签处理查询列表接口
	 */
	@Override
	public String searchExchangeList(Date fromDateTime, Date toDateTime, String rebookQueryOptionType, Integer orderID,
			String ticketNO) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenQueryExchangeRequest>";
			xml += "<FromDateTime>" + DateUtil.toStrDate(fromDateTime, "yyyy-MM-dd HH:mm:ss").replace(" ", "T")
					+ "</FromDateTime>";
			xml += "<ToDateTime>" + DateUtil.toStrDate(toDateTime, "yyyy-MM-dd") + "</ToDateTime>";
			xml += "<RebookQueryOptionType>" + rebookQueryOptionType + "</RebookQueryOptionType>";
			if (orderID != null) {
				xml += "<OrderID>" + orderID + "</OrderID>";
			}
			if (ticketNO != null) {
				xml += "<TicketNO>" + ticketNO + "</TicketNO >";
			}
			xml += "</OpenQueryExchangeRequest>";
			xml += "</Request>";
			String responseContent = GetStubUtil.getSearchExchangeListSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 改签操作接口
	 */
	@Override
	public String modifyExchangeList(String rebookProcessStatusType, String rbkId, String remark, Integer sequence,
			String airLineCode, String airLine, String passengerName, String flight, String dPort, String aPort,
			Date takeOffTime, String subClass, String ticketNO, String recordNo, Float rebookingQueryFee,
			String rebookType) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenModifyExchangeRequest>";
			xml += "<RebookProcessStatusType>" + rebookProcessStatusType + "</RebookProcessStatusType>";
			xml += "<RebookType>" + rebookType + "</RebookType> <OpenApiModifyExchangeItems>";
			xml += "<OpenApiModifyExchangeItem> <Sequence>" + sequence + "</Sequence>";
			xml += "<AirLineCode>" + airLineCode + "</AirLineCode> <AirLine>" + airLine + "</AirLine>";
			xml += "<PassengerName>" + passengerName + "</PassengerName>";
			xml += "<Flight>" + flight + "</Flight> <DPort>" + dPort + "</DPort>";
			xml += "<APort>" + aPort + "</APort>";
			xml += "<TakeOffTime>" + DateUtil.toStrDate(takeOffTime, "yyyy-MM-dd HH:mm:ss").replace(" ", "T")
					+ "</TakeOffTime>";
			xml += "<SubClass>" + subClass + "</SubClass> <TicketNO>" + ticketNO + "</TicketNO>";
			xml += "<RecordNo>" + recordNo + "</RecordNo>";
			xml += "<RebookingQueryFee>" + rebookingQueryFee + "</RebookingQueryFee>";
			xml += "</OpenApiModifyExchangeItem>";
			xml += "</OpenApiModifyExchangeItems> <RbkId>0</RbkId>";
			xml += "<Remark>" + remark + "</Remark>";
			xml += "</OpenModifyExchangeRequest>";
			System.out.println(xml);
			String responseContent = GetStubUtil.getModifyExchangeListSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 改签确认接口
	 */
	@Override
	public String confirmRebookAmountService(Integer rbkid, String modifyRemark, String passengername,
			Float agencyTotalRebookFee) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenConfirmRebookAmountRequest>";
			xml += "<OpenRebookConfirmItems>";
			xml += "<OpenRebookConfirmItem>";
			xml += "<Rbkid>" + rbkid + "</Rbkid>";
			xml += "<ModifyRemark>" + modifyRemark + "</ModifyRemark>";
			xml += "<OpenRebookOrderInfos>";
			xml += "<OpenRebookOrderInfo> <Passengername>" + passengername + "</Passengername>";
			xml += "<AgencyTotalRebookFee>" + agencyTotalRebookFee + "</AgencyTotalRebookFee>";
			xml += "</OpenRebookOrderInfo>";
			xml += "</OpenRebookOrderInfos>";
			xml += "</OpenRebookConfirmItem>";
			xml += "</OpenRebookConfirmItems>";
			xml += "</OpenConfirmRebookAmountRequest> </Request>";
			String responseContent = GetStubUtil.getConfirmRebookAmountServiceSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 出票单查询接口
	 */
	@Override
	public String searchIssueBill(Date orderBeginDateTime, Date orderEndDateTime, Long issueBillID,
			String issueStatus) {
		String response = "";
		try {
			String username = CtripService.username;
			String md5_password = MD5Util.MD5(username + "#" + CtripService.password);
			String xml = "<?xml version=\"1.0\"?>";
			xml += "<Request UserName=\"" + username + "\" UserPassword=\"" + md5_password + "\">";
			xml += "<OpenSearchIssueBillRequest>";
			xml += "<OrderBeginDateTime>" + DateUtil.toStrDate(orderBeginDateTime, "yyyy-MM-dd HH:mm:ss")
					+ "</OrderBeginDateTime>";
			xml += "<OrderEndDateTime>" + DateUtil.toStrDate(orderEndDateTime, "yyyy-MM-dd HH:mm:ss")
					+ "</OrderEndDateTime>";
			xml += "<IssueBillID>" + issueBillID + "</IssueBillID>";
			if (issueStatus != null && !"".equals(issueStatus)) {
				xml += "<IssueStatus>" + issueStatus + "</IssueStatus>";
			}
			xml += "</OpenSearchIssueBillRequest>";
			xml += "</Request>";
			String responseContent = GetStubUtil.getSearchIssueBillSoapStub().handle(xml);
			response = getResponse(responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	public static String openAPIRequest(String xml, String apiType) {
		try {
			String response = HttpClientUtil.sendSoapHttpPost(CtripService.openapi_url, getOpenApiRequestXml(xml, apiType));
			System.out.println(response);
			return response;
		} catch (Exception e) {
			//logger.error("政策api请求出错！", e);
		}
		return "";
	}
	
	public static String getOpenApiRequestXml(String xml, String apiType) throws UnsupportedEncodingException {
		String gzipRequestBytes = new Base64Encoder().encode(ZipUtil.gZip(xml.getBytes("UTF-8")));
		String request = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + 
				"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n" + 
				"  <soap:Body>\r\n" + 
				"    <ProcessRequest xmlns=\"http://tempuri.org/\">\r\n" + 
				"      <userId>41</userId>\r\n" + 
				"      <password>5C8A5B5C5685EDC89F0DEF4A665BEB5F</password>\r\n" + 
				"      <apiType>" + apiType + "</apiType>\r\n" + 
				"      <gzipRequestBytes>" +gzipRequestBytes+ "</gzipRequestBytes>\r\n" + 
				"    </ProcessRequest>\r\n" + 
				"  </soap:Body>\r\n" + 
				"</soap:Envelope>";
		return request;
	}

	public static void main(String[] args) throws IOException {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		CommisionPolicyServiceImpl service = ctx.getBean(CommisionPolicyServiceImpl.class);
		String request = "<?xml version=\"1.0\"?>"
				+ "<PublishFareRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
				+ "<PublishFareInfoList><PublishFareInfo FareID=\"\" TripType=\"BOTH\" IsActivated=\"\" Owner=\"\" SeatClass=\"\" "
				+ "DepCity=\"\" ArrCity=\"\" IsPrivate=\"\" "
				+ " ExternalID=\"\" /></PublishFareInfoList></PublishFareRequest>";
		String responseContent = openAPIRequest(request, "12");
		responseContent = responseContent.substring(responseContent.indexOf("<ProcessRequestResult>") + 22, responseContent.indexOf("</ProcessRequestResult>"));
		String responseXml = new String(ZipUtil.unGZip(Base64Util.decode(responseContent.getBytes("UTF-8"))));
		PublishFareResponse response = XStreamUtil.fromXml(responseXml);
		for (PublishFareInfo fare : response.getPublishFareInfoList()) {
			CommisionPolicy policy = CtripPolicyUtil.toSysPolicy(fare);
			
		}
	}

	/**
	 * 结果集先base64解码，再解压缩获取
	 * 
	 * @param responseContent
	 * @return
	 * @throws IOException
	 */
	public String getResponse(String responseContent) throws IOException {
		return new String(ZipUtil.unGZip(Base64Util.decode(responseContent.getBytes("UTF-8"))));
	}

}
